import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:katana_router/katana_router.dart';
import 'package:thal/backstage/blueprint/group_chat_print.dart';
import 'package:thal/backstage/blueprint/user_print.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';
import 'package:thal/backstage/control_room/group_chat_room.dart';
import 'package:thal/backstage/control_room/user_room.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/backstage/toolkit/widgets/authentication_focus_curtain.dart'
    show AuthenticationSpotlight;
import 'package:thal/backstage/toolkit/widgets/stage_whisper.dart';
import 'package:thal/playbill/messenger/group_detail_production.dart';

part 'group_list_production.page.dart';

/// 群聊列表页面
@PagePath('/group-list')
class GroupListProduction extends StatelessWidget {
  const GroupListProduction({super.key});

  @pageRouteQuery
  static RouteQuery query() => const _$GroupListProductionQuery().call();

  @override
  Widget build(BuildContext context) {
    final groupChatRoom = GlobalStateProvider.groupChatRoomOf(context);
    final userRoom = GlobalStateProvider.userRoomOf(context);

    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AssetManifest.screenBackground),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 固定顶部标题
              _buildHeader(context),

              // 可滚动内容区域
              Expanded(
                child: SingleChildScrollView(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      10.h.heightBox,

                      // 群聊列表
                      Observer(
                        builder: (_) {
                          return Column(
                            children:
                                groupChatRoom.groupChats
                                    .map(
                                      (groupChat) => _buildGroupCard(
                                        context,
                                        groupChat,
                                        groupChatRoom,
                                        userRoom,
                                      ),
                                    )
                                    .toList(),
                          );
                        },
                      ),
                      50.h.heightBox,
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建固定顶部标题
  Widget _buildHeader(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: ColorPalette.iconBg,
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.chevron_left_rounded,
                color: ColorPalette.black,
                size: 36.sp,
              ),
            ),
          ),
          12.w.widthBox,

          // 标题
          Expanded(
            child: Center(
              child: Text('Group Chat')
                  .fontSize(24.sp)
                  .textColor(ColorPalette.black)
                  .carterOne(weight: FontWeight.w400),
            ),
          ),
          52.w.widthBox,
        ],
      ),
    );
  }

  /// 构建群聊卡片
  Widget _buildGroupCard(
    BuildContext context,
    GroupChatPrint groupChat,
    GroupChatRoom groupChatRoom,
    UserRoom userRoom,
  ) {
    // 获取当前用户
    final currentUser = userRoom.fetchCurrentUser();
    final isJoined =
        currentUser != null && groupChat.memberIds.contains(currentUser.id);

    // 获取成员列表（最多4个）
    final members =
        groupChat.memberIds
            .take(3)
            .map((id) => userRoom.fetchUserById(id))
            .where((user) => user != null)
            .cast<UserPrint>()
            .toList();

    return Padding(
      padding: EdgeInsets.only(bottom: 32.h),
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          // 阴影效果 - 第二层
          Positioned(
            left: 26.w,
            top: 16.h,
            right: 26.w,
            bottom: -16.h,
            child: Container(
              width: 306.w,
              height: 138.h,
              decoration: BoxDecoration(
                color: const Color(0x4CF6FCFF),
                borderRadius: BorderRadius.circular(16.r),
              ),
            ),
          ),
          // 阴影效果 - 第一层
          Positioned(
            left: 12.w,
            top: 8.h,
            right: 12.w,
            bottom: -8.h,
            child: Container(
              width: 333.w,
              height: 143.h,
              decoration: BoxDecoration(
                color: const Color(0x99F6FCFF),
                borderRadius: BorderRadius.circular(16.r),
              ),
            ),
          ),
          // 主卡片
          Container(
            width: 358.w,
            height: 142.h,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(16.r),
              boxShadow: [
                BoxShadow(
                  color: ColorPalette.black.withValues(alpha: 0.05),
                  blurRadius: 10,
                  offset: Offset(0, 5.h),
                ),
              ],
            ),
            child: Row(
              children: [
                // 左边图片
                Container(
                  width: 190.w,
                  height: 110.h,
                  margin: EdgeInsets.all(16.w),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(12.r),
                    child: Image.asset(groupChat.imageUrl, fit: BoxFit.cover),
                  ),
                ),

                // 右边内容
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Spacer(),

                      // 群聊名称
                      Text(groupChat.title)
                          .fontSize(20.sp)
                          .textColor(ColorPalette.black)
                          .arimo(weight: FontWeight.w700),
                      const Spacer(),

                      // 用户头像
                      SizedBox(
                        height: 28.w,
                        child: Stack(
                          children: [
                            ...members.asMap().entries.map((entry) {
                              final index = entry.key;
                              final user = entry.value;
                              return Positioned(
                                left: (index * 20).toDouble(),
                                child: Container(
                                  width: 28.w,
                                  height: 28.w,
                                  decoration: BoxDecoration(
                                    shape: BoxShape.circle,
                                  ),
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(14.r),
                                    child: Image.asset(
                                      user.avatar,
                                      fit: BoxFit.cover,
                                    ),
                                  ),
                                ),
                              );
                            }),

                            // 更多成员提示
                            if (groupChat.memberIds.length > 3)
                              Positioned(
                                left: (members.length * 20).toDouble(),
                                child: Container(
                                  width: 28.w,
                                  height: 28.w,
                                  decoration: BoxDecoration(
                                    color: ColorPalette.black,
                                    shape: BoxShape.circle,
                                  ),
                                  child: Center(
                                    child: Text(
                                          '${groupChat.memberIds.length - 3}+',
                                        )
                                        .arimo(weight: FontWeight.w700)
                                        .fontSize(10.sp)
                                        .textColor(Colors.white),
                                  ),
                                ),
                              ),
                          ],
                        ),
                      ),

                      const Spacer(),

                      // 加入/聊天按钮
                      Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 40.w,
                          vertical: 4.h,
                        ),
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            begin: Alignment(0.00, 0.50),
                            end: Alignment(1.00, 0.50),
                            colors: [ColorPalette.blue2, ColorPalette.blue1],
                          ),
                          borderRadius: BorderRadius.circular(15.r),
                        ),
                        child: Text(
                          isJoined ? 'Chat' : 'Join',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 14.sp,
                            fontWeight: FontWeight.w700,
                          ),
                        ),
                      ).withTapEffect(
                        onTap: () {
                          if (currentUser == null) {
                            // 未登录，弹出登录弹窗
                            AuthenticationSpotlight.illuminate(context);
                          } else {
                            if (isJoined) {
                              // 已加入，跳转到群聊详情页面
                              context.router.push(
                                GroupDetailProduction.query(
                                  groupId: groupChat.id,
                                ),
                              );
                            } else {
                              // 未加入，显示加入确认弹窗
                              _showJoinConfirmationDialog(
                                context,
                                groupChat,
                                groupChatRoom,
                                userRoom,
                              );
                            }
                          }
                        },
                      ),
                      const Spacer(),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 显示加入群聊确认弹窗
  void _showJoinConfirmationDialog(
    BuildContext context,
    GroupChatPrint groupChat,
    GroupChatRoom groupChatRoom,
    UserRoom userRoom,
  ) {
    showDialog(
      context: context,
      barrierDismissible: true,
      barrierColor: ColorPalette.black.withValues(alpha: 0.7),
      builder:
          (context) => Dialog(
            backgroundColor: Colors.transparent,
            insetPadding: EdgeInsets.symmetric(horizontal: 32.w),
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(24.r),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 顶部装饰
                  Container(
                    height: 40.h,
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [const Color(0xFFE0F2FE), Colors.white],
                      ),
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(24.r),
                        topRight: Radius.circular(24.r),
                      ),
                    ),
                  ),

                  // 内容区域
                  Padding(
                    padding: EdgeInsets.symmetric(
                      horizontal: 24.w,
                      vertical: 24.h,
                    ),
                    child: Column(
                      children: [
                        // 群聊图片
                        Container(
                          width: 200.w,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(12.r),
                          ),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(12.r),
                            child: Image.asset(
                              groupChat.imageUrl,
                              fit: BoxFit.fitWidth,
                            ),
                          ),
                        ),
                        20.h.heightBox,

                        // 标题
                        Text('Join Group?')
                            .fontSize(24.sp)
                            .textColor(ColorPalette.black)
                            .arimo(weight: FontWeight.w700),
                        12.h.heightBox,

                        // 描述
                        Text(groupChat.title)
                            .fontSize(16.sp)
                            .textColor(const Color(0xFF666666))
                            .arimo(weight: FontWeight.w400),
                        8.h.heightBox,
                        Text(groupChat.description, textAlign: TextAlign.center)
                            .fontSize(12.sp)
                            .textColor(const Color(0xFF999999))
                            .arimo(weight: FontWeight.w400),
                        32.h.heightBox,

                        // 按钮
                        Row(
                          children: [
                            // 取消按钮
                            Expanded(
                              child: GestureDetector(
                                onTap: () => Navigator.of(context).pop(),
                                child: Container(
                                  height: 48.h,
                                  decoration: BoxDecoration(
                                    color: const Color(0xFFF5F5F5),
                                    borderRadius: BorderRadius.circular(12.r),
                                  ),
                                  child: Center(
                                    child: Text('Cancel')
                                        .fontSize(16.sp)
                                        .textColor(ColorPalette.black)
                                        .arimo(weight: FontWeight.w700),
                                  ),
                                ),
                              ),
                            ),
                            12.w.widthBox,
                            // 加入按钮
                            Expanded(
                              child: GestureDetector(
                                onTap: () {
                                  Navigator.of(context).pop();
                                  // 添加到群聊
                                  final currentUser =
                                      userRoom.fetchCurrentUser();
                                  if (currentUser != null) {
                                    groupChatRoom.joinGroupChat(
                                      currentUser.id,
                                      groupChat.id,
                                    );
                                    StageWhisper.cheer('Joined successfully');
                                  }
                                },
                                child: Container(
                                  height: 48.h,
                                  decoration: BoxDecoration(
                                    gradient: LinearGradient(
                                      begin: Alignment(0.00, 0.50),
                                      end: Alignment(1.00, 0.50),
                                      colors: [
                                        ColorPalette.blue2,
                                        ColorPalette.blue1,
                                      ],
                                    ),
                                    borderRadius: BorderRadius.circular(12.r),
                                  ),
                                  child: Center(
                                    child: Text('Join')
                                        .fontSize(16.sp)
                                        .textColor(Colors.white)
                                        .arimo(weight: FontWeight.w700),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
    );
  }
}
